<template>
  <div>
    <el-card style="border-radius: 12px">
      <el-row :gutter="20">
        <el-form-item label="部门：">
          <el-select
            placeholder="请选择"
            v-model="SecDepartmentNumber"
            filterable
          >
            <el-option
              v-for="department in AlldepartmentsData"
              :key="department.departmentNumber"
              :value="department.departmentNumber"
              :label="department.departmentName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 20px">
          <el-button
            type="primary"
            icon="Search"
            @click="getdepartmentData()"
            v-button="`btn.Department.search`"
          >
            搜索
          </el-button>
          <el-button @click=";(SecDepartmentNumber = ''), getdepartmentData()">
            重置
          </el-button>
        </el-form-item>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="departmentView"
            v-button="`btn.Department.add`"
          >
            添加部门
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="departmentData" style="margin: 10px 0px" border>
        <el-table-column
          label="序号"
          align="center"
          type="index"
          prop="index"
          hidden="false"
        ></el-table-column>
        <el-table-column
          label="部门编号"
          align="center"
          prop="number"
        ></el-table-column>
        <el-table-column
          label="部门名称"
          align="center"
          prop="departmentName"
        ></el-table-column>
        <!-- <el-table-column label="负责人" align="center" prop="personLiable"></el-table-column>
        <el-table-column label="负责人工号" align="center" prop="jobNumber"></el-table-column>
        <el-table-column label="负责人电话" align="center" prop="mobile"></el-table-column> -->
        <el-table-column
          label="部门描述"
          align="center"
          prop="describes"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template #="{ row, $index }">
            <el-tooltip
              effect="dark"
              content="修改部门信息"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="small"
                type="primary"
                icon="Edit"
                @click="updatedepartmentView(row)"
                v-button="`btn.Department.update`"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="删除部门"
              placement="top"
              :enterable="false"
            >
              <el-popconfirm
                :title="`删除: ${row.departmentName}?`"
                icon="Delete"
                icon-color="red"
                @confirm="deletedepartment(row.id)"
              >
                <template #reference>
                  <el-button
                    size="small"
                    type="danger"
                    icon="Delete"
                    v-button="`btn.Department.delete`"
                  ></el-button>
                </template>
                /
              </el-popconfirm>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 
   v-model:current-page ：当前页
   v-model:page-size：设置每页展示数据的条数
         -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[5, 10, 15, 20]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="prev, pager, next, jumper, -> ,total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getdepartmentData"
      />
    </el-card>
    <!-- 添加部门对话框 -->
    <el-dialog
      :title="departmentParams.id ? '修改部门' : '新增部门'"
      v-model="addDialogVisible"
      width="30%"
    >
      <el-form
        style="width: 90%"
        label-width="100px"
        :model="departmentParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="部门编号" prop="number">
          <el-input
            placeholder="请输入部门编号"
            v-model="departmentParams.number"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName">
          <el-input
            placeholder="请输入部门名称"
            v-model="departmentParams.departmentName"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="负责人工号" prop="jobNumber">
          <el-input placeholder="请输入工号" v-model="departmentParams.jobNumber"></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="personLiable">
          <el-input placeholder="请输入部门负责人姓名" v-model="departmentParams.personLiable"></el-input>
        </el-form-item>
        <el-form-item label="负责人电话" prop="mobile">
          <el-input placeholder="负责人电话" v-model="departmentParams.mobile"></el-input>
        </el-form-item> -->
        <el-form-item label="部门描述" prop="describes">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="部门描述"
            v-model="departmentParams.describes"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addOrUpdatedepartment">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqdepartmentData,
  reqAddOrUpdatedepartmentData,
  reqDeletedepartmentData,
  reqGetAlldepartment,
  reqdepartmentpageData,
} from '@/api/department'
import type {
  departments,
  departmentInformationResponseData,
  departmentInformation,
  ResponseData,
  departmentlists,
  Alldepartment,
} from '@/api/department/type'
import { Check, Close } from '@element-plus/icons-vue'
import { number } from 'echarts'

// 当前页码
let pageNo = ref<number>(1)
// 定义每页展示数据
let limit = ref<number>(5)
// 定义展示数据的总数
let total = ref<number>(0)

// 定义已有部门的数据
let departmentData = ref<departments>([])
// 回去搜索框部门编号
let SecDepartmentNumber = ref<string>()

let AlldepartmentsData = ref<departmentlists>([])

const getAlldepartment = async () => {
  let result: Alldepartment = await reqGetAlldepartment()
  if (result.code == 200) {
    // 存储已有品牌的总数
    AlldepartmentsData.value = result.data
  }
}

//  定义新增部门数据
let departmentParams = reactive<any>({
  number: '',
  departmentName: '',
  describes: '',
})
const validatorNumber = (rule: any, value: any, callback: any) => {
  const reg = /^(?=.*[a-zA-Z])(?=.*\d).+$/
  if (reg.test(value)) {
    callback()
  } else {
    callback(new Error('内容必须包含至少一个字母和一个数字'))
  }
}

const validatorName = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('部门名称不能为空'))
  }
}
const validatorJobNumber = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('工号不能为空'))
  }
}

const validatorMobile = (rule: any, value: any, callback: any) => {
  let reg = /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/
  let n = reg.test(value)
  if (value && n) {
    callback()
  } else if (!value) {
    callback(new Error('电话不能为空'))
  } else {
    callback(new Error('电话格式有误'))
  }
}

const validatorPersonLiable = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('负责人不能为空'))
  }
}
const rules = {
  number: [{ required: true, trigger: 'blur', validator: validatorNumber }],
  departmentName: [
    { required: true, trigger: 'blur', validator: validatorName },
  ],
  jobNumber: [
    {
      required: true,
      type: 'number',
      trigger: 'blur',
      validator: validatorJobNumber,
    },
  ],
  personLiable: [
    {
      required: true,
      type: 'number',
      trigger: 'blur',
      validator: validatorPersonLiable,
    },
  ],
  mobile: [
    {
      required: true,
      type: 'number',
      trigger: 'blur',
      validator: validatorMobile,
    },
  ],
}
//添加会议对话框
let addDialogVisible = ref<boolean>(false)

// 获取el-form 组件实例
let formRef = ref()

const getdepartmentData = async (page = 1) => {
  pageNo.value = page
  let params = {
    number: SecDepartmentNumber.value ? SecDepartmentNumber.value : '',
    currentPage: pageNo.value,
    pageSize: limit.value,
  }

  let result: departmentInformationResponseData = await reqdepartmentpageData(
    params,
  )
  console.log(result)
  if (result.code == 200) {
    // 存储已有品牌的总数
    total.value = result.data.total
    departmentData.value = result.data.records
  }
}
// 组件挂载完毕
onMounted(() => {
  getAlldepartment()
  getdepartmentData()
})
// 更改分页器大小
const handleSizeChange = () => {
  getdepartmentData()
}
// 添加或修改部门方法
const addOrUpdatedepartment = async () => {
  // 发送请求之前对整个表单进行校验
  await formRef.value.validate()
  let result: ResponseData = await reqAddOrUpdatedepartmentData(
    departmentParams,
  )
  console.log(result)

  if (result.code == 200) {
    addDialogVisible.value = false
    ElNotification({
      type: 'success',
      message: departmentParams.id ? '修改部门成功' : '添加部门成功',
    }),
      // 再次发请求更新所有数据
      getdepartmentData(departmentParams.id ? pageNo.value : 1)
  } else {
    ElNotification({
      type: 'error',
      message: departmentParams.id ? '修改部门失败' : '添加部门失败',
    })
  }
}
// 修改部门信息 row 为当前信息
const updatedepartmentView = (row: departmentInformation) => {
  nextTick(() => {
    for (const key in departmentParams) {
      formRef.value.clearValidate(key)
    }
  })
  ;(addDialogVisible.value = true), Object.assign(departmentParams, row)
}
// 删除确认框按钮回调
const deletedepartment = async (id: number) => {
  console.log('delete')

  // 点击确定按钮删除请求发送
  let result = await reqDeletedepartmentData(id)
  if (result.code == 200) {
    ElNotification({
      type: 'success',
      message: '删除成功',
    })
    getdepartmentData(
      departmentData.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElNotification({
      type: 'error',
      message: '删除失败',
    })
  }
}
// 表单取消按钮
const cancel = () => {
  addDialogVisible.value = false
}
// 表单确定按钮
const departmentView = () => {
  addDialogVisible.value = true
  //  清空收集 的数据
  ;(departmentParams.id = 0),
    (departmentParams.number = ''),
    (departmentParams.describes = ''),
    (departmentParams.departmentName = ''),
    nextTick(() => {
      for (const key in departmentParams) {
        formRef.value.clearValidate(key)
      }
    })
}
</script>

<style scoped lang="scss"></style>
